import LoadingWrap from '@/components/LoadingWrap';
import ResultWrap from '@/components/ResultWrap';
import { ArticleApi, CategoryApi } from '@/services/cms/CmsController';
import {
    ModalForm,
    ProFormText,
    ProFormTextArea,
    ProFormTreeSelect,
} from '@ant-design/pro-components';
import { useAccess, useNavigate, useRequest, UseRequestProvider } from '@umijs/max';
import { Button, Form, message, Result, Space } from 'antd';
import { useEffect, useState } from 'react';


const Settings: React.FC<{
    id: number | String | null;
    is_new?: boolean;
    content?: String;
    onClose?: () => void;
    onFinish?: (data?: { id: number | String }) => void;
}> = ({ id, onClose, onFinish, content, is_new }) => {
    const navigate = useNavigate()
    const access = useAccess()
    const [doPublish, setDoPublish] = useState(false)

    useEffect(() => { setDoPublish(false) }, [id, is_new])

    const [form] = Form.useForm<Cms.ArtileSetting>();
    let { loading: loadingArticle, error, run: fetch_article } = useRequest(() => id ? ArticleApi.fetch(id) : Promise.resolve({}), {
        refreshDeps: [id],
        throwOnError: true,
        onSuccess: form.setFieldsValue
    });
    let { loading, run: save } = useRequest(async (data) => {
        let res = await (id ? ArticleApi.update(id, { content, ...data }) : ArticleApi.create({ content, ...data }))
        if (doPublish) {
            await ArticleApi.publish(res.id);
        }
        return res
    },
        {
            manual: true,
            onError: () => {
                message.error('操作失败');
            },
            onSuccess(data, params) {
                message.success('操作成功');
                onFinish && onFinish(data)
                onClose && onClose()
                doPublish && navigate(-1)
            },
        })

    let show_publish = form.getFieldValue("status") != 1

    return (
        <ModalForm<Cms.ArtileSetting> title="文章设置" open={id != null || is_new} form={form} width={500} autoFocusFirstInput
            loading={loading} submitTimeout={2000} onFinish={async (d) => { setDoPublish(false); save(d) }}
            submitter={{
                render(props, dom) {
                    return <Space>{dom}{show_publish && <Button onClick={() => { setDoPublish(true); props.submit() }} color='primary' variant="outlined">发布</Button>}</Space>
                },
            }}
            modalProps={{
                destroyOnClose: true,
                onCancel: onClose,
                maskClosable: false,
                okText: "保存",
            }}
        >
            <LoadingWrap loading={loadingArticle}>
                <ResultWrap error={error} reload={fetch_article}>
                    <ProFormText name="title" label="标题" rules={[{ required: true, min: 2, max: 64 },]} />
                    <ProFormText name="keywords" label="关键词" />
                    <ProFormText name="fromurl" label="转载来源网址" />
                    <ProFormText name="image" label="封面图" />
                    <ProFormTreeSelect name="categories" request={CategoryApi.list} label="栏目" fieldProps={{ multiple: true, fieldNames: { label: 'name', value: 'id', }, }}></ProFormTreeSelect>
                    <ProFormTextArea name="description" label="简介" />
                </ResultWrap>
            </LoadingWrap>
        </ModalForm>
    );
};

export default Settings;
